package net.kingborn.core.util;

import java.math.BigInteger;

/**
 * 数学工具
 * 
 * @author David Chen
 *
 */
public class MathKit {

	/**
	 * 进制转换(2~36)
	 * 
	 * @param input
	 * @param sourceBase
	 * @param targetBase
	 * @return
	 */
	public static String baseConvert(String input, int sourceBase, int targetBase) {
		if (sourceBase < 2 || sourceBase > 36 || targetBase < 2 || targetBase > 36) {
			throw new IllegalArgumentException("进制必须在2~26之间");
		}
		
		BigInteger decimalResult = BigInteger.ZERO;
		String result = "";
		
		BigInteger temp = BigInteger.ONE;
		int len = input.length();
		for (int i = len - 1; i >= 0; i--) {
			if (i != len - 1)
				temp = temp.multiply(BigInteger.valueOf(sourceBase));
			int num = changeDec(input.charAt(i));
			decimalResult = decimalResult.add(temp.multiply(BigInteger.valueOf(num)));
		}
		
		BigInteger val = new BigInteger(targetBase + "");
		while (decimalResult.compareTo(BigInteger.ZERO) != 0) {
			temp = decimalResult.mod(val);
			decimalResult = decimalResult.divide(val);
			char ch = changToNum(temp);
			result = ch + result;
		}
		
		return result;
	}
	
	// 数字转换为字符
	private static char changToNum(BigInteger temp) {
		int n = temp.intValue();

		if (n >= 10 && n <= 35)
			return (char) (n - 10 + 'A');

		else if (n >= 36 && n <= 61)
			return (char) (n - 36 + 'a');

		else
			return (char) (n + '0');
	}

	// 十进制转换中把字符转换为数
	private static int changeDec(char ch) {
		int num = 0;
		if (ch >= 'A' && ch <= 'Z')
			num = ch - 'A' + 10;
		else if (ch >= 'a' && ch <= 'z')
			num = ch - 'a' + 36;
		else
			num = ch - '0';
		return num;
	}
	
}
